package fishBids.group3.behaviour.bank;

import es.upm.agents.ontology.ToGetAmount;
import es.upm.agents.ontology.ToGetAmountResponse;
import fishBids.group3.AgBank;
import fishBids.group3.behaviour.bank.model.Account;
import fishBids.group3.common.Constants;
import fishBids.group3.utils.Utils;
import jade.content.lang.Codec;
import jade.content.onto.Ontology;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

public class BankGetAmountBehaviour extends CyclicBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = -2472621384661749131L;
	
	public BankGetAmountBehaviour(AgBank agBank, Codec codec, Ontology ontology){
		this.agBank = agBank;
		this.codec =  codec;
		this.ontology = ontology;
		
	}

	@Override
	public void action() {

		//System.out.println("Bank >>>> Get amount running......");
		MessageTemplate mt1 = MessageTemplate.and( 
		    	MessageTemplate.MatchLanguage(codec.getName()), 
		    	MessageTemplate.and(MessageTemplate.MatchOntology(ontology.getName()),
		    	MessageTemplate.and(MessageTemplate.MatchProtocol(Constants.GET_AMOUNT),
		    	MessageTemplate.MatchPerformative(ACLMessage.QUERY_REF)))); 
		
			ACLMessage msg = this.agBank.receive(mt1);
			if (msg != null){
					ToGetAmount toGetAmount = (ToGetAmount) Utils.extractContent(this.agBank, msg);
//					System.out.println( "Bank>>> GetAmount QUERY_REF message arrived, product type: " + 
//							toGetAmount.getProductType().getType() );
					Account account = (Account)this.agBank.getAgentsAccounts().get(msg.getSender().getName());
					if(account != null){
						Float amount = (Float) account.getItems().get(toGetAmount.getProductType().getType());
						ToGetAmountResponse toGetAmountResponse = new ToGetAmountResponse();
						toGetAmountResponse.setAmount( (float) (amount == null ? 0 : amount.doubleValue()));
						toGetAmountResponse.setProductType(toGetAmount.getProductType());
									
						//TODO retrieve the money in the bank account
						Utils.sendMessageWithConcept(ACLMessage.INFORM,
									codec, ontology, msg.getSender(),
								Constants.GET_AMOUNT, this.agBank,
								toGetAmountResponse);
						//System.out.println( "Bank>>>  Sending getAmount INFORM" );
						return;
					}else {
						//System.out.println( "Bank>>>  Sending getAmount REFUSE" );
						Utils.sendMessage(ACLMessage.REFUSE,
								codec, ontology, msg.getSender(),
							Constants.GET_MONEY, this.agBank);
						return;
					
					}								
				
				
			}else {
				block();
			}

		}



	AgBank agBank;
	Codec codec;
	Ontology ontology;

}
